<template>
  <div>
    <div class="pageTitleWhole">
      <a-breadcrumb>
        <a-breadcrumb-item>人员及组织架构</a-breadcrumb-item>
      </a-breadcrumb>
    </div>
    <div class="pageContentWhole">
      <a-row>
        <a-col :span="7" class="leftTree">
          <h2>组织架构</h2>
          <a-tree v-if="jk" :load-data="onLoadData" :tree-data="treeData" @select="queryUsers" />
        </a-col>
        <a-col :span="17" class="rightData">
          <a-row class="partMargin">
            <a-col :span="12">
              <h2>{{currentSeletedNode.title}}（{{count}}人）</h2>
            </a-col>
            <a-col :span="12" style="textAlign: right">
              <a
                v-show="currentSeletedNode.key !== '-1'"
                class="linkStyle"
                @click="modifyDept"
              >修改部门名称</a>
              <a v-show="currentSeletedNode.key !== '-1'" class="linkStyle" @click="addDept">添加子部门</a>
              <a
                v-show="currentSeletedNode.key !== '-1' && currentSeletedNode.isDefault !== 1"
                class="linkStyle"
                @click="deleteDept"
              >删除部门</a>
            </a-col>
          </a-row>

          <a-form layout="inline">
            <a-form-item label="姓名">
              <a-input v-model="searchForm.name" />
            </a-form-item>
            <a-form-item label="账号">
              <a-input v-model="searchForm.account" />
            </a-form-item>

            <a-form-item>
              <a-button type="primary" @click="handleSubmit">查询</a-button>
            </a-form-item>
            <a-form-item>
              <a-button
                type="primary"
                v-show="currentSeletedNode.key !== '-1'"
                @click="handleCreate"
              >+ 创建成员</a-button>
            </a-form-item>
          </a-form>

          <a-table
            :columns="columns"
            :data-source="tableData"
            class="tableMargin"
            :pagination="false"
            rowKey="uiId"
          >
            <span slot="head" slot-scope="record">
              <a-avatar size="large" :src="record.headPortrait || defaultAvatar" />
            </span>
            <span slot="name" slot-scope="record">
              {{record.name}}
              <img v-if="record.isLeader===1" :src="xing" />
            </span>
            <a slot="edit" slot-scope="record" @click="editMember(record.uiId)">编辑</a>
          </a-table>
        </a-col>
      </a-row>

      <a-modal
        :title="optTitle"
        :visible="visible"
        :confirm-loading="confirmLoading"
        @ok="handleOk"
        @cancel="handleCancel"
      >
        <a-form-model ref="ruleForm" :model="form" :rules="rules" layout="inline">
          <a-form-model-item label="部门名称" prop="deptName">
            <a-input v-model="form.deptName" autocomplete="off" style="width: 375px"></a-input>
          </a-form-model-item>
        </a-form-model>
      </a-modal>

      <development-member
        :visible="visible2"
        :uiId="edituiId"
        :deptId="deptId"
        @set-visible="setVisible"
      />
    </div>
  </div>
</template>

<script>
import { queryDeptList, queryDeptUserList, addUserDept, updateUserDept, deleteUserDept } from '@/api/systemPersonnelManage'
import { Tree } from 'ant-design-vue'
import deptMember from './deptMember'
import xing from '@/../static/images/xing.png'
import defaultAvatar from '@/../static/images/defaultAvatar.png'

export default {
  data () {
    const columns = [
      {
        title: '序号',
        width: 60,
        customRender: (text, row, index) => {
          return index + 1
        }
      },
      {
        width: 60,
        scopedSlots: { customRender: 'head' }
      },
      {
        title: '姓名',
        ellipsis: true,
        scopedSlots: { customRender: 'name' }
      },
      {
        title: '职务',
        dataIndex: 'position',
        ellipsis: true
      },
      {
        title: '所属部门',
        dataIndex: 'deptName',
        ellipsis: true
      },
      {
        title: '账号',
        dataIndex: 'account'
      },
      {
        title: '操作',
        width: 70,
        scopedSlots: { customRender: 'edit' }
      }
    ]

    return {
      jk: false,
      xing,
      defaultAvatar,
      treeData: [],
      currentSeletedNode: { key: 0, title: '', isDefault: 1 },
      count: 0,
      columns,
      tableData: [],
      searchForm: { name: '', account: '' },
      // modal 1
      optTitle: '', // 0添加子部门 1修改部门名称
      visible: false,
      confirmLoading: false,
      form: { deptName: '' },
      rules: {
        deptName: [
          { required: true, message: '部门名称必须输入', trigger: 'blur' },
          { max: 50, message: '限制输入50个字符', trigger: 'blur' }
        ]
      },
      // modal 2
      edituiId: '', // 新增不传，编辑传uiId
      deptId: '',
      visible2: false
    }
  },
  components: {
    [Tree.name]: Tree,
    [deptMember.name]: deptMember
  },
  methods: {
    onLoadData (treeNode) {
      return new Promise(resolve => {
        if (treeNode.dataRef.children) {
          resolve()
          return
        }
        queryDeptList({ parentId: treeNode.dataRef.key }).then(rsp => {
          let childrenData = []
          rsp.data.forEach((value, index) => {
            childrenData.push({
              title: value.name,
              key: value.deptId,
              isDefault: value.isDefault
            })
          })
          treeNode.dataRef.children = childrenData
          this.treeData = [...this.treeData]
          resolve()
        })
      })
    },
    queryUsers (selectedKeys, e) {
      queryDeptUserList({ deptId: e.node.dataRef.key }).then(rsp => {
        this.tableData = rsp.data
        this.count = rsp.data.length
        this.currentSeletedNode = e.node.dataRef

        this.deptId = e.node.dataRef.key // 触发更新modal数据
      })
    },
    handleSubmit () {
      queryDeptUserList({ deptId: this.currentSeletedNode.key, name: this.searchForm.name, account: this.searchForm.account }).then(rsp => {
        this.tableData = rsp.data
        this.count = rsp.data.length
      })
    },
    initPage () {
      this.jk = false
      queryDeptList({ parentId: 0 }).then(rsp => {
        let initData = []
        rsp.data.forEach((value, index) => {
          initData.push({
            title: value.name,
            key: value.deptId,
            isDefault: value.isDefault
          })
        })
        initData.push({
          title: '已冻结账号',
          key: '-1',
          isLeaf: true
        })
        this.treeData = initData
        this.jk = true
        return initData[0]
      }).then(data => {
        // 默认加载所有
        queryDeptUserList({ deptId: data.key }).then(rsp => {
          this.tableData = rsp.data
          this.count = rsp.data.length
          this.currentSeletedNode = data

          this.deptId = data.key // 触发更新modal数据
        })
      })
    },
    // 本地处理 treeData
    searchOption (option, arr, type = 'delect') {
      for (let s = 0; s < arr.length; s++) {
        if (arr[s].key === option.key) {
          if (type === 'delect') {
            arr.splice(s, 1)
          } else if (type === 'modify') {
            arr[s] = option
          } else if (type === 'add') {
            arr[s].children.push({
              key: option.ckey,
              title: option.title
            })
          }
          break
        } else if (arr[s].children && arr[s].children.length > 0) { // 递归条件
          this.searchOption(option, arr[s].children, type)
        } else {
          continue
        }
      }
    },
    modifyDept () {
      if (!this.$root._bc.editDept) {
        this.$message.error('您无此权限！')
        return
      }
      this.optTitle = '修改部门名称'
      this.form.deptName = this.currentSeletedNode.title
      this.visible = true
    },
    addDept () {
      if (!this.$root._bc.createDept) {
        this.$message.error('您无此权限！')
        return
      }
      this.optTitle = '添加子部门'
      this.form.deptName = ''
      this.visible = true
    },
    deleteDept () {
      let _t = this
      this.$confirm({
        title: '删除部门后，其下属的子部门将一并删除，确认删除？',
        okText: '删除',
        okType: 'danger',
        onOk () {
          deleteUserDept({ deptId: _t.currentSeletedNode.key }).then(() => {
            // _t.searchOption(_t.currentSeletedNode, _t.treeData)
            // _t.treeData = [..._t.treeData]
            _t.initPage()
          })
        }
      })
    },
    handleOk (e) {
      this.confirmLoading = true
      let newname = this.form.deptName
      if (this.optTitle === '添加子部门') {
        let parameter = { parentId: this.currentSeletedNode.key, name: newname }
        addUserDept(parameter).then(rsp => {
          this.$message.success('添加部门成功！')
          this.visible = false
          this.$refs['ruleForm'].resetFields()
          this.searchOption(Object.assign([], this.currentSeletedNode, { title: newname, ckey: rsp.data }), this.treeData, 'add')
          this.treeData = [...this.treeData]
          setTimeout(() => { this.confirmLoading = false }, 1000)
        }).catch(() => {
          this.confirmLoading = false
        })
      } else if (this.optTitle === '修改部门名称') {
        updateUserDept({ deptId: this.currentSeletedNode.key, name: newname }).then(rsp => {
          this.$message.success('修改部门名称成功！')
          this.visible = false
          this.$refs['ruleForm'].resetFields()
          this.searchOption(Object.assign(this.currentSeletedNode, { title: newname }), this.treeData, 'modify')
          this.treeData = [...this.treeData]
          setTimeout(() => { this.confirmLoading = false }, 1000)
        }).catch(() => {
          this.confirmLoading = false
        })
      }
    },
    handleCancel (e) {
      this.visible = false
      this.$refs['ruleForm'].resetFields()
    },
    handleCreate () {
      if (!this.$root._bc.create) {
        this.$message.error('您无此权限！')
        return
      }
      this.visible2 = true
      this.edituiId = ''
    },
    editMember (uiId) {
      if (!this.$root._bc.edit) {
        this.$message.error('您无此权限！')
        return
      }
      this.visible2 = true
      this.edituiId = uiId
      this.deptId = '' // 不可删除，用于子组件部门信息查询
    },
    setVisible (b) {
      this.visible2 = b
      this.handleSubmit()
    }
  },
  mounted () {
    this.$nextTick(() => {
      this.initPage()
    })
  }
}
</script>

<style lang="less" scoped>
.leftTree {
  overflow-x: auto;
  min-height: 500px;
}

.rightData {
  padding-left: 20px;
  border-left: 1px solid #f0f2f5;

  a.linkStyle {
    margin-right: 5px;
  }
}
</style>
